<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Auth;
use \Illuminate\Auth\Authenticatable;

class PublicController extends Controller 
{
		// 登录
    public function login(Request $request) {
    	if($request->isMethod('POST')) {
    		$request -> validate([
    			'uname'			=>		'required|min:2|max:16',
    			'password'	=>		'required|min:6|max:18',
    			'captcha'		=> 		'required|captcha'
    			]);
    		$data = $request -> only('uname','password');
            $data['active'] = 1;
    		if(Auth::attempt($data)) {
    			return redirect('/admin/user/index');
    		}else {
    			return redirect('/public/login')->with('status','用户名或密码错误');
    		}
    	}else {
    		return view('public.login');
    	}
    }

    // 注册
    public function register(Request $request) {

        if($request->isMethod('POST')) {
            $request -> validate([
                'uname'     =>      'required|min:2|max:16',
                'password'  =>      'required|min:6|max:18',
                'phone'     =>      'required|integer',
                'email'     =>      'required|email',
                'captcha'   =>      'required|captcha'
                ]);
            $data = $request -> except('_token','captcha');
            $data['password'] = bcrypt($data['password']);
            $data['active'] = 1;
            $data['role_id'] = mt_rand(0,1);

            $user = new User;
            if($user -> create($data)) {
                return redirect('/public/login');
            }else {
                return redirect('/public/register');
            }

        }else {
    	   return view('public.register');
        }

    }


    public function logout() {
        Auth::logout();
        return redirect('/public/login');
    }

}
